package com.example.singing.view;

import com.example.singing.MainApp;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import java.io.File;
import javafx.animation.ScaleTransition;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.util.Duration;

/**
 * 主界面
 */
public class MainView {
    private MainApp mainApp;
    private User currentUser;
    private BorderPane view;
    private DashboardView dashboardView; // 保存DashboardView引用，便于刷新数据

    public MainView(MainApp mainApp, User currentUser) {
        this.mainApp = mainApp;
        this.currentUser = currentUser;
        createView();
    }

    /**
     * 创建主界面
     */
    private void createView() {
        // 主容器
        BorderPane mainPane = new BorderPane();
        mainPane.setPadding(new Insets(10));

        // 顶部导航栏
        HBox topBar = createTopBar();
        mainPane.setTop(topBar);

        // 左侧菜单
        VBox leftMenu = createLeftMenu();
        mainPane.setLeft(leftMenu);

        // 中间内容区域 - 默认显示仪表盘
        dashboardView = new DashboardView();
        mainPane.setCenter(dashboardView.getView());

        this.view = mainPane;
    }

    /**
     * 创建顶部导航栏
     */
    private HBox createTopBar() {
        HBox topBar = new HBox(20);
        topBar.setPadding(new Insets(15));
        topBar.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
        topBar.setStyle("-fx-background-color: #2c3e50; -fx-background-radius: 5;");

        // 系统标题
        Label title = new Label("歌唱比赛评分系统");
        title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: white;");

        // 用户信息
        HBox userBox = new HBox(10);
        userBox.setAlignment(javafx.geometry.Pos.CENTER_RIGHT);

        Label userName = new Label(currentUser.getFullName() + " (" + currentUser.getRole() + ")");
        userName.setStyle("-fx-font-size: 14px; -fx-text-fill: white;");

        Circle avatar = new Circle(15, Color.WHITE);
        avatar.setStroke(Color.LIGHTGRAY);

        Button logoutBtn = new Button("退出");
        logoutBtn.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white; -fx-font-weight: bold; " +
                "-fx-background-radius: 5px;");
        logoutBtn.setOnAction(e -> {
            // 确认退出
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认退出");
            alert.setHeaderText("确定要退出系统吗？");
            alert.setContentText("您将返回到登录界面");

            if (alert.showAndWait().get() == ButtonType.OK) {
                mainApp.showLoginView();
            }
        });

        userBox.getChildren().addAll(userName, avatar, logoutBtn);

        // 添加图片（替换搜索框）
        ImageView logoImage = new ImageView();
        try {
            // 加载用户指定的图片（使用正确的路径）
            String imagePath = "/resources/OIP-C.png";
            Image image = new Image(getClass().getResourceAsStream(imagePath));
            logoImage.setImage(image);
            logoImage.setFitHeight(70);  // 设置图片高度
            logoImage.setFitWidth(200);  // 设置图片宽度
            logoImage.setPreserveRatio(true);  // 保持图片比例
            logoImage.setSmooth(true);   // 图片平滑显示
        } catch (Exception e) {
            System.err.println("无法加载图片: " + e.getMessage());
            // 如果classpath方式失败，尝试使用文件系统路径
            try {
                String filePath = "src/main/java/resources/OIP-C.jpg";
                File file = new File(filePath);
                if (file.exists()) {
                    Image image = new Image(file.toURI().toString());
                    logoImage.setImage(image);
                    logoImage.setFitHeight(50);
                    logoImage.setFitWidth(150);
                    logoImage.setPreserveRatio(true);
                    logoImage.setSmooth(true);
                } else {
                    System.err.println("文件不存在: " + filePath);
                }
            } catch (Exception ex) {
                System.err.println("文件系统方式加载图片失败: " + ex.getMessage());
            }
        }

        HBox.setHgrow(userBox, Priority.ALWAYS);  // 让用户信息区域占据剩余空间
        topBar.getChildren().addAll(title, logoImage, userBox);

        return topBar;
    }

    /**
     * 创建左侧菜单
     */
    private VBox createLeftMenu() {
        VBox menu = new VBox(10);
        menu.setPadding(new Insets(20, 10, 20, 10));
        menu.setStyle("-fx-background-color: white; -fx-background-radius: 5;");
        menu.setPrefWidth(200);

        // 菜单项
            String[] menuItems = {"仪表盘", "比赛管理", "队伍管理", "评分管理", "智能分析", "历史查询", "系统设置"};

        for (String item : menuItems) {
            Button btn = new Button(item);
            btn.setPrefWidth(180);
            btn.setMinWidth(180);
            btn.setMaxWidth(180);
            btn.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
            btn.setStyle("-fx-background-color: transparent; -fx-text-fill: #546e7a; -fx-font-size: 14px; " +
                    "-fx-padding: 10 15;");

            // 当前选中的菜单项样式
            final Button currentBtn = btn;
            final String menuItem = item;

            if (item.equals("仪表盘")) {
                btn.setStyle("-fx-background-color: #e3f2fd; -fx-text-fill: #1e88e5; -fx-font-weight: bold;");
            }

            // 鼠标悬停效果 - 添加平滑放大动画
            btn.setOnMouseEntered(e -> {
                currentBtn.setStyle("-fx-background-color: #e3f2fd; -fx-text-fill: #1e88e5;");
                
                // 创建放大动画
                ScaleTransition scaleUp = new ScaleTransition(Duration.millis(200), currentBtn);
                scaleUp.setToX(1.05);
                scaleUp.setToY(1.05);
                scaleUp.play();
            });

            // 鼠标离开效果 - 添加平滑缩小动画
            btn.setOnMouseExited(e -> {
                if (!menuItem.equals("仪表盘")) {
                    currentBtn.setStyle("-fx-background-color: transparent; -fx-text-fill: #546e7a;");
                }
                
                // 创建缩小动画
                ScaleTransition scaleDown = new ScaleTransition(Duration.millis(200), currentBtn);
                scaleDown.setToX(1.0);
                scaleDown.setToY(1.0);
                scaleDown.play();
            });

            // 添加点击事件切换内容区域
            btn.setOnAction(e -> {
                BorderPane mainPane = (BorderPane) view;
                
                // 根据菜单项显示不同的视图
                if (menuItem.equals("仪表盘")) {
                    // 刷新Dashboard数据并显示
                    if (dashboardView != null) {
                        dashboardView.refreshData();
                        mainPane.setCenter(dashboardView.getView());
                    } else {
                        dashboardView = new DashboardView();
                        mainPane.setCenter(dashboardView.getView());
                    }
                } else if (menuItem.equals("比赛管理")) {
                    mainPane.setCenter(new CompetitionView().getView());
                } else if (menuItem.equals("队伍管理")) {
                    mainPane.setCenter(new TeamView(currentUser).getView());
                } else if (menuItem.equals("评分管理")) {
                    // 显示评分界面，但在返回Dashboard时需要刷新数据
                    ScoringView scoringView = new ScoringView(currentUser);
                    mainPane.setCenter(scoringView.getView());
                } else if (menuItem.equals("系统设置")) {
                    // 显示系统设置界面
                    SettingsView settingsView = new SettingsView(currentUser);
                    mainPane.setCenter(settingsView.getView());
                } else if (menuItem.equals("历史查询")) {
                    mainPane.setCenter(new HistoryView(currentUser).getView());
                } else if (menuItem.equals("智能分析")) {
                    // 显示智能分析界面
                    SmartAnalysisView smartAnalysisView = new SmartAnalysisView();
                    mainPane.setCenter(smartAnalysisView.getView());
                }
                
                // 更新菜单项样式
                for (javafx.scene.Node node : menu.getChildren()) {
                    if (node instanceof Button) {
                        Button menuBtn = (Button) node;
                        if (menuBtn.getText().equals(menuItem)) {
                            menuBtn.setStyle("-fx-background-color: #e3f2fd; -fx-text-fill: #1e88e5; -fx-font-weight: bold;");
                        } else {
                            menuBtn.setStyle("-fx-background-color: transparent; -fx-text-fill: #546e7a;");
                        }
                    }
                }
            });

            menu.getChildren().add(btn);
        }

        return menu;
    }

    /**
     * 获取界面视图
     */
    public BorderPane getView() {
        return view;
    }
}